import Vue from 'vue'
import VueRouter from 'vue-router'
import { hasToken } from '@/utils/cookie'
import { MessageBox } from 'element-ui';
Vue.use(VueRouter)
const routes = [
  // 配置重定向
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('./../views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('./../views/Register.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('./../views/Home.vue'),
    children: [
      {
        path: '',
        redirect: 'index'
      },
      {
        path: 'index',
        name: 'index',
        component: () => import('./../views/child/Index.vue')
      },
      {
        path: 'classes',
        name: 'classes',
        component: () => import('./../views/child/Classes.vue')
      },
      {
        path: 'student',
        name: 'student',
        component: () => import('./../views/child/Student.vue')
      },
      {
        path: 'mine',
        name: 'mine',
        component: () => import('./../views/child/Mine.vue')
      },
    ]

  }
]

const router = new VueRouter({
  routes
})
// 路由全局前置导航守卫
// 白名单
const whitePages = ['/login', '/register']
router.beforeEach((to, from, next) => {
  if (hasToken()) {
    // 有登录，直接放行
    whitePages.includes(to.path)?next('/home/index'):next()
    } 
   else {
    // 没有登录，判断是否在白名单内
    if (whitePages.includes(to.path)) {
      next()
    } else {
      // 提示先登录
      MessageBox.confirm('你没有登录，请登录', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //  确定
        next('/login')
      }).catch(() => {
        //  取消
        next('/login')
      });
    }
  }
})

export default router
